package com.training.bt.controller;

import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;

import com.training.bt.entity.*;
import com.training.bt.enums.Role;
import com.training.bt.security.util.JwtUtil;
import com.training.bt.user.dto.OtherDTO;
import com.training.bt.user.dto.UserLoginDTO;
import com.training.bt.user.dto.UserRegisterDTO;
import com.training.bt.user.dto.UserResponseDTO;
import com.training.bt.user.service.UserService;

@RestController
@RequestMapping("api/auth")
@RequiredArgsConstructor
public class AuthController {
    private final UserService userService;
    private final JwtUtil jwtUtil;

    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody @Valid UserRegisterDTO dto) {
        userService.register(dto);
        return ResponseEntity.ok("注册成功");
    }

    @PostMapping("/login")
    public ResponseEntity<UserResponseDTO> login(@RequestBody @Valid UserLoginDTO dto) {
        User user = userService.login(dto);
        String token = jwtUtil.generateToken(user);
        UserResponseDTO response = new UserResponseDTO();
        response.setId(user.getId());
        response.setRole(user.getRole().name());
        response.setToken(token);
        response.setUsername(user.getUsername());
        response.setPasskey(user.getPasskey());
        return ResponseEntity.ok(response);
    }

    @GetMapping("/profile")
    public ResponseEntity<UserResponseDTO> profile() {

        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (!(principal instanceof User user)) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }

        UserResponseDTO dto = new UserResponseDTO();

        dto.setId(user.getId());
        dto.setRole(user.getRole().name());
        dto.setUsername(user.getUsername());
        dto.setToken(null);
        dto.setPasskey(user.getPasskey());
        dto.setExperience(user.getExperience());

        return ResponseEntity.ok(dto);
    }

    @GetMapping("/getRole")
    public ResponseEntity<Role> getRole() {
        User user = userService.getRole();
        return ResponseEntity.ok(user.getRole());
    }

    @GetMapping("/getOther")
    public ResponseEntity<OtherDTO> getOther(Long id) {
        User user = userService.getOther(id);

        OtherDTO dto = new OtherDTO();
        dto.setId(id);
        dto.setUsername(user.getUsername());

        return ResponseEntity.ok(dto);
    }
}
